pub mod server;
pub mod client;
pub mod protocol;

pub use server::McpServer;
pub use client::McpClient;
pub use protocol::{McpMessage, McpRequest, McpResponse};

use anyhow::Result;
use tracing::info;

/// MCP (Model Context Protocol) integration
#[derive(Debug)]
pub struct McpIntegration {
    server: McpServer,
    clients: Vec<McpClient>,
}

impl McpIntegration {
    /// Create a new MCP integration
    pub async fn new() -> Result<Self> {
        info!("Initializing MCP integration");

        let server = McpServer::new().await?;
        let clients = Vec::new();

        Ok(Self {
            server,
            clients,
        })
    }

    /// Create a new MCP integration synchronously
    pub fn new_sync() -> Self {
        info!("Initializing MCP integration (sync)");

        let server = McpServer::new_sync();
        let clients = Vec::new();

        Self {
            server,
            clients,
        }
    }
    
    /// Start the MCP server
    pub async fn start_server(&mut self, port: u16) -> Result<()> {
        info!("Starting MCP server on port {}", port);
        self.server.start(port).await
    }
    
    /// Add a new MCP client
    pub async fn add_client(&mut self, endpoint: &str) -> Result<()> {
        info!("Adding MCP client: {}", endpoint);
        let client = McpClient::new(endpoint).await?;
        self.clients.push(client);
        Ok(())
    }
    
    /// Send a request to all connected clients
    pub async fn broadcast_request(&self, request: McpRequest) -> Result<Vec<McpResponse>> {
        info!("Broadcasting MCP request to {} clients", self.clients.len());
        
        let mut responses = Vec::new();
        for client in &self.clients {
            match client.send_request(&request).await {
                Ok(response) => responses.push(response),
                Err(e) => {
                    tracing::error!("Failed to send request to client: {}", e);
                }
            }
        }
        
        Ok(responses)
    }
    
    /// Get server status
    pub fn server_status(&self) -> bool {
        self.server.is_running()
    }
    
    /// Get number of connected clients
    pub fn client_count(&self) -> usize {
        self.clients.len()
    }
}
